import json
from loguru import logger
import requests
from read_search_file import  return_headers, return_content_type_post_headers, js_code
import execjs
from datetime import datetime
from xhs_headers_generator import get_xhs_headers

def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)
def get_original_balance_budget(cookies=None, account_id=None, log_callback=None):
    url = "https://ad.xiaohongshu.com/api/leona/rtb/account/balance"

    headers = return_headers(account_id=account_id)
    generateXs = get_xhs_headers(f'/api/leona/rtb/account/balance?vSellerId={account_id}')
    # generateXs = execjs.compile(js_code).call("get_xhs_headers", f'/api/leona/rtb/account/balance?vSellerId={account_id}')

    headers['x-s'] = generateXs['X-s']
    headers['x-t'] = str(generateXs['X-t'])

    params = {"vSellerId": str(account_id)}
    response = requests.get(url, headers=headers, cookies=cookies, params=params)

    res_json = response.json()
    if res_json.get('code') == 0:
        res_data = res_json.get('data')
        accountBudget = res_data.get('accountBudget')
        # log_message(log_callback, f'子账号ID初始预算获取成功:{accountBudget}', "green")
        return int(accountBudget)
    else:
        error_message = f'子账号ID初始预算获取失败:【{account_id}】获取失败'
        log_message(log_callback, error_message, "red")
        logger.error(error_message)
        raise Exception(error_message)  # 抛出异常

def update_balance_budget(cookies=None, account_id=None, budget=None, adjustment=None, log_callback=None):
    headers = return_content_type_post_headers(account_id=account_id)
    url = "https://ad.xiaohongshu.com/api/leona/rtb/account/budget"

    generateXs = get_xhs_headers(f'/api/leona/rtb/account/budget')
    # generateXs = execjs.compile(js_code).call("get_xhs_headers", f'/api/leona/rtb/account/budget')

    headers['x-s'] = generateXs['X-s']
    headers['x-t'] = str(generateXs['X-t'])

    budget = budget + adjustment

    data = {
        "type": 0,
        "limitDayBudget": 1,
        "budget": budget,
        "smartSwitch": 0
    }
    data = json.dumps(data, separators=(',', ':'))
    response = requests.put(url, headers=headers, cookies=cookies, data=data)

    res_json = response.json()
    if res_json.get('code') == 0:
        log_message(log_callback, f'子账号ID初始预算修改成功:{account_id}', "green")
        logger.info(f'子账号ID初始预算修改成功:{account_id}')
    else:
        fail_msg = res_json.get('msg')
        error_message = f'子账号ID:【{account_id}】修改预算失败: {fail_msg}'
        log_message(log_callback, error_message, "red")
        raise Exception(error_message)  # 抛出异常



def select_campaign_by_name(cookies=None, account_id=None, log_callback=None):
    today = datetime.now().date().strftime("%Y-%m-%d")

    headers = return_content_type_post_headers(account_id=account_id)
    url = "https://ad.xiaohongshu.com/api/leona/rtb/campaign/list"
    generateXs = execjs.compile(js_code).call("get_xhs_headers", f'/api/leona/rtb/campaign/list')

    headers['x-s'] = generateXs['X-s']
    headers['x-t'] = str(generateXs['X-t'])

    data = {
        "startTime": today,
        "endTime": today,
        "name": "每日调整",
        "pageNum": 1,
        "pageSize": 20,
        "source": "web"
    }
    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(url, headers=headers, cookies=cookies, data=data)

    res_json = response.json()
    if res_json.get('code') == 0:
        list_data = res_json.get('data', {}).get('list', [])
        if list_data:
            first_ele = list_data[0]
            campaignId = first_ele.get('campaignId')
            log_message(log_callback, f'查询当前账号【每日调整】计划成功: {account_id}', "purple")
            logger.info(f'查询当前账号每日调整计划成功:{account_id}')
            change_campaign_status_open(cookies=cookies, account_id=account_id, campaign_id=campaignId, generateXs=generateXs, log_callback=log_callback)
            change_campaign_status_close(cookies=cookies, account_id=account_id, campaign_id=campaignId, generateXs=generateXs, log_callback=log_callback)
    else:
        fail_msg = res_json.get('msg')
        error_message = f'查询当前账号【每日调整】计划失败:{account_id} - {fail_msg}'
        log_message(log_callback, error_message, "red")
        raise Exception(error_message)  # 抛出异常




def change_campaign_status_open(cookies=None, account_id=None, campaign_id=None, generateXs=None, log_callback=None):
    headers = return_content_type_post_headers(account_id=account_id)

    url = "https://ad.xiaohongshu.com/api/leona/rtb/campaign/batch/status"
    # generateXs = execjs.compile(js_code).call("get_xhs_headers", f'/api/leona/rtb/campaign/list')

    headers['x-s'] = generateXs['X-s']
    headers['x-t'] = str(generateXs['X-t'])

    data = {
        "ids": [
            campaign_id
        ],
        "actionType": 1
    }
    data = json.dumps(data, separators=(',', ':'))
    response = requests.put(url, headers=headers, cookies=cookies, data=data)

    res_json = response.json()
    if res_json.get('code') == 0:
        log_message(log_callback, f'子账号ID: {account_id} - 每日调整 计划状态开启 - 成功', "green")
        logger.info(f'子账号ID: {account_id} - 每日调整 计划状态开启成功')
    else:
        fail_msg = res_json.get('msg')
        error_message = f'子账号ID: {account_id} - 每日调整 - 计划状态开启失败 - {fail_msg}'
        log_message(log_callback, error_message, "red")
        raise Exception(error_message)  # 抛出异常

def change_campaign_status_close(cookies=None, account_id=None, campaign_id=None, generateXs=None, log_callback=None):
    headers = return_content_type_post_headers(account_id=account_id)

    url = "https://ad.xiaohongshu.com/api/leona/rtb/campaign/batch/status"
    # generateXs = execjs.compile(js_code).call("get_xhs_headers", f'/api/leona/rtb/campaign/list')

    headers['x-s'] = generateXs['X-s']
    headers['x-t'] = str(generateXs['X-t'])

    data = {
        "ids": [
            campaign_id
        ],
        "actionType": 2
    }
    data = json.dumps(data, separators=(',', ':'))
    response = requests.put(url, headers=headers, cookies=cookies, data=data)

    res_json = response.json()
    if res_json.get('code') == 0:
        log_message(log_callback, f'子账号ID: {account_id} - 每日调整 计划状态关闭 - 成功', "green")
        logger.info(f'子账号ID: {account_id} - 每日调整 计划状态开启成功')
    else:
        fail_msg = res_json.get('msg')
        error_message = f'子账号ID: {account_id} - 每日调整 - 计划状态关闭 - 失败 - {fail_msg}'
        log_message(log_callback, error_message, "red")
        raise Exception(error_message)  # 抛出异常


